<template>
  <div class="probe-container">
    <!-- 左侧元件列表 -->
    <div class="component-list-panel">
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索元件"
          prefix-icon="el-icon-search"
          clearable
        />
      </div>
      <div class="component-tree">
        <!-- 一级目录固定 -->
        <div class="tree-node">
          <div class="node-header" @click="expandedLevel1 = !expandedLevel1" style="cursor:pointer;">
            <i :class="expandedLevel1 ? 'el-icon-arrow-down' : 'el-icon-arrow-right'"></i>
            元件列表
          </div>
          <div v-show="expandedLevel1">
            <div
              v-for="(level3Group, level2Name) in filteredComponentTree"
              :key="level2Name"
              class="sub-category"
            >
              <div
                class="sub-header"
                @click="toggleTypeExpand(level2Name)"
                style="cursor:pointer;"
              >
                <i :class="expandedTypes[level2Name] ? 'el-icon-arrow-down' : 'el-icon-arrow-right'"></i>
                {{ level2Name }}
              </div>

              <div v-show="expandedTypes[level2Name]" class="component-list">
                <div
                  v-for="(components, level3Name) in level3Group"
                  :key="level3Name"
                  class="sub-sub-category"
                >
                  <!-- 如果三级目录名为空字符串，说明没有三级目录，直接渲染组件列表 -->
                  <template v-if="level3Name === ''">
                    <div
                      v-for="component in components"
                      :key="component.id"
                      class="component-item"
                      :class="{ active: activeComponent && activeComponent.id === component.id }"
                      @click="selectComponent(component)"
                    >
                      {{ component.name }}
                    </div>
                  </template>
                  <template v-else>
                    <div
                      class="sub-sub-header"
                      @click="toggleSubTypeExpand(level2Name + '-' + level3Name)"
                      style="cursor:pointer; margin-left: 16px;"
                    >
                      <i :class="expandedSubTypes[level2Name + '-' + level3Name] ? 'el-icon-arrow-down' : 'el-icon-arrow-right'"></i>
                      {{ level3Name }}
                    </div>
                    <div v-show="expandedSubTypes[level2Name + '-' + level3Name]" class="component-list" style="margin-left: 32px;">
                      <div
                        v-for="component in components"
                        :key="component.id"
                        class="component-item"
                        :class="{ active: activeComponent && activeComponent.id === component.id }"
                        @click="selectComponent(component)"
                      >
                        {{ component.name }}
                      </div>
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 三维模型展示 -->
    <div class="model-viewer" v-if="activeComponent && activeComponent.drawingThree">
      <div class="model-container">
        <!-- <div ref="threeContainer" class="model-three-container"></div> -->
        <model-stl
          :key="activeComponent.id"
          :src="activeComponent.drawingThree"
        />
        <!-- <div class="model-tools">
          <el-button size="mini" icon="el-icon-zoom-in" @click="zoom(1.1)" circle></el-button>
          <el-button size="mini" icon="el-icon-zoom-out" @click="zoom(0.9)" circle></el-button>
          <el-button size="mini" icon="el-icon-full-screen" @click="toggleFullscreen" circle></el-button>
          <el-button size="mini" icon="el-icon-refresh" @click="rotateModel" circle></el-button>
        </div> -->
      </div>
    </div>

    <!-- 右侧参数面板 -->
    <div class="parameter-panel" v-if="activeComponent">
      <div class="panel-header">
        <h3>支杆参数</h3>
        <el-button
          type="primary"
          size="mini"
          @click="openParameterEditor"
          v-hasPermi="['system:probeComponent:edit']"
        >
          <i class="el-icon-edit"></i> 编辑参数
        </el-button>
      </div>

      <!-- 动态参数分组展示 -->
      <div
        class="parameter-group"
        v-for="(group, index) in parsedParameters"
        :key="index"
      >
        <h4 class="group-title">{{ group.name }}</h4>
        <div class="parameter-items-container">
          <div
            class="parameter-item"
            v-for="(param, idx) in group.data"
            :key="idx"
          >
            <span class="param-name">{{ param.name }}：</span>
            <span class="param-value">
              {{ param.value }}{{ param.unit }}
            </span>
          </div>
        </div>
      </div>

    </div>

    <!-- 参数编辑对话框 -->
    <el-dialog title="参数编辑" :visible.sync="editDialogVisible" width="600px">
      <el-form label-position="top">
        <el-row :gutter="20">
          <el-col
            :span="12"
            v-for="(param, index) in editParameters"
            :key="index"
          >
            <el-form-item :label="param.label">
              <el-input v-model="param.value">
                <template #append>{{ param.unit }}</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveParameters">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProbeComponent,
  updateProbeComponent,
  getProbeComponent,
  delProbeComponent,
} from "@/api/system/probeComponent";
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';  // 新增
import { ModelStl } from 'vue-3d-model';
export default {
  components: {
    ModelStl
  },
  data(){
    return {
      searchKeyword: "",
      activeComponent: null,
      components: [],
      editDialogVisible: false,
      scale: 1,
      isFullscreen: false,
      editParameters: [],
      expandedLevel1: true,
      expandedTypes: {},
      expandedSubTypes: {}, // 新增三级目录展开状态
      threeScene: null,
      threeCamera: null,
      threeRenderer: null,
      threeLoader: null,
      threeModel: null,
      animationId: null,
      controls: null,
      modelScale: { x: 1, y: 1, z: 1 },
      modelRotation: { x: 0, y: 0, z: 0 },
    };
  },
  computed: {
    // 过滤组件列表，支持搜索
    filteredComponents() {
      if (!this.searchKeyword) return this.components;
      const keyword = this.searchKeyword.toLowerCase();
      return this.components.filter(
        (c) =>
          c.name.toLowerCase().includes(keyword) ||
          c.type.toLowerCase().includes(keyword) ||
          c.id.toString().includes(keyword)
      );
    },
    // 根据过滤后的组件，构造树形结构：{ typeName: [components] }
    filteredComponentTree() {
      const tree = {};
      this.filteredComponents.forEach((comp) => {
        const typeParts = comp.type.split("/");
        if (typeParts.length === 1) {
          // 没有斜杠，二级目录是type，三级目录用特殊key存放name列表
          const level2 = typeParts[0];
          if (!tree[level2]) {
            tree[level2] = {};
          }
          // 用空字符串作为三级目录key，存放name列表
          if (!tree[level2][""]) {
            tree[level2][""] = [];
          }
          tree[level2][""].push(comp);
        } else if (typeParts.length === 2) {
          // 有斜杠，二级目录是前半部分，三级目录是后半部分
          const level2 = typeParts[0];
          const level3 = typeParts[1];
          if (!tree[level2]) {
            tree[level2] = {};
          }
          if (!tree[level2][level3]) {
            tree[level2][level3] = [];
          }
          tree[level2][level3].push(comp);
        } else {
          // 如果type中有多个斜杠，按需求可扩展，这里暂时只处理两级
          // 也可以合并后面的部分作为三级目录
          const level2 = typeParts[0];
          const level3 = typeParts.slice(1).join("/");
          if (!tree[level2]) {
            tree[level2] = {};
          }
          if (!tree[level2][level3]) {
            tree[level2][level3] = [];
          }
          tree[level2][level3].push(comp);
        }
      });
      return tree;
    },
    // 解析当前选中元件的参数JSON，返回数组格式方便渲染
    parsedParameters() {
      if (!this.activeComponent || !this.activeComponent.parameter) return [];
      try {
        return JSON.parse(this.activeComponent.parameter);
      } catch (e) {
        return [];
      }
    },
  },
  mounted() {
    this.loadComponents();
  },
  methods: {
    // initThree() {
    //   const container = this.$refs.threeContainer;
    //   const width = container.clientWidth;
    //   const height = container.clientHeight;
    //   console.log('threeContainer size:', container.clientWidth, container.clientHeight);
    //   // 创建场景
    //   this.threeScene = new THREE.Scene();

    //   // 创建相机
    //   this.threeCamera = new THREE.PerspectiveCamera(45, width / height, 0.1, 1000);
    //   this.threeCamera.position.set(0, 1.5, 3);

    //   // 创建渲染器
    //   this.threeRenderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
    //   this.threeRenderer.setSize(width, height);
    //   this.threeRenderer.setClearColor(0xf0f0f0, 1); // 背景透明
    //   container.appendChild(this.threeRenderer.domElement);

    //   // 添加环境光
    //   const ambientLight = new THREE.AmbientLight(0xffffff, 0.8);
    //   this.threeScene.add(ambientLight);

    //   // 添加方向光
    //   const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
    //   directionalLight.position.set(5, 10, 7);
    //   this.threeScene.add(directionalLight);
    //   const gridHelper = new THREE.GridHelper(10, 10);
    //   this.threeScene.add(gridHelper);
    //   // 创建GLTFLoader
    //   this.threeLoader = new GLTFLoader();
    //   this.controls = new OrbitControls(this.threeCamera, this.threeRenderer.domElement);
    //   this.controls.enableDamping = true; // 开启阻尼（惯性）
    //   this.controls.dampingFactor = 0.05;
    //   this.controls.screenSpacePanning = false;
    //   this.controls.minDistance = 1;  // 最小缩放距离
    //   this.controls.maxDistance = 100; // 最大缩放距离
    //   this.controls.maxPolarAngle = Math.PI / 2; // 限制垂直旋转角度
    //   this.animate = this.animate.bind(this);
    //   // 开始渲染循环
    //   this.animate();
    // },

  // 渲染循环
    // animate() {
    //   this.animationId = requestAnimationFrame(this.animate);

    //   // // 如果模型存在，可以旋转模型
    //   // if (this.threeModel) {
    //   //   this.threeModel.rotation.y += 0.01;
    //   // }
    //         // 更新controls
    //   if (this.controls) {
    //     this.controls.update();
    //   }

    //   this.threeRenderer.render(this.threeScene, this.threeCamera);
    // },

  // 清理Three.js资源
    // disposeThree() {
    //   if (this.animationId) {
    //     cancelAnimationFrame(this.animationId);
    //     this.animationId = null;
    //   }
    //   if (this.controls) {
    //     this.controls.dispose();
    //     this.controls = null;
    //   }
    //   if (this.threeRenderer) {
    //     this.threeRenderer.dispose();
    //     this.threeRenderer.domElement && this.threeRenderer.domElement.remove();
    //     this.threeRenderer = null;
    //   }
    //   if (this.threeScene) {
    //     this.threeScene.clear();
    //     this.threeScene = null;
    //   }
    //   this.threeCamera = null;
    //   this.threeLoader = null;
    //   this.threeModel = null;
    // },
    // loadModel(url) {
    //   console.log('加载模型路径:', url);
    //   if (!this.threeLoader) return;

    //   // 如果已有模型，先移除
    //   if (this.threeModel) {
    //     this.threeScene.remove(this.threeModel);
    //     this.threeModel.traverse((child) => {
    //       if (child.geometry) child.geometry.dispose();
    //       if (child.material) {
    //         if (Array.isArray(child.material)) {
    //           child.material.forEach(mat => mat.dispose());
    //         } else {
    //           child.material.dispose();
    //         }
    //       }
    //     });
    //     this.threeModel = null;
    //   }

    //   this.threeLoader.load(
    //     url,
    //     (gltf) => {
    //       console.log('模型加载成功', gltf);
    //       this.threeModel = gltf.scene;
    //       this.threeScene.add(this.threeModel);

    //       // 适当缩放和居中模型
    //       const box = new THREE.Box3().setFromObject(this.threeModel);
    //       const size = box.getSize(new THREE.Vector3());
    //       const center = box.getCenter(new THREE.Vector3());

    //       this.threeModel.position.x += -center.x;
    //       this.threeModel.position.y += -center.y;
    //       this.threeModel.position.z += -center.z;
    //       // 根据模型大小调整相机距离
    //       const maxDim = Math.max(size.x, size.y, size.z);
    //       const fov = this.threeCamera.fov * (Math.PI / 180);
    //       let cameraZ = Math.abs(maxDim / 2 / Math.tan(fov / 2));
    //       cameraZ *= 1.5; // 预留空间
    //       this.threeCamera.position.z = cameraZ;

    //       this.threeCamera.lookAt(center);
    //     },
    //     undefined,
    //     (error) => {
    //       console.error("加载模型失败", error);
    //     }
    //   );
    // },
    async loadComponents() {

      const res = await listProbeComponent();
      this.components = res.rows || [];
  //     this.components = [
  //   {
  //     "createBy": null,
  //     "createTime": null,
  //     "updateBy": null,
  //     "updateTime": null,
  //     "remark": null,
  //     "id": 2,
  //     "createdBy": "职工1号",
  //     "createdTime": "2014-11-20",
  //     "updatedBy": "职工34号",
  //     "updatedTime": "2025-04-25",
  //     "parameter": "[{\"name\":\"基本参数\",\"data\":[{\"name\":\"长度\",\"value\":\"12023423423343\",\"unit\":\"mm\"},{\"name\":\"形状\",\"value\":\"圆筒\",\"unit\":\"\"},{\"name\":\"外径\",\"value\":\"30\",\"unit\":\"mm\"},{\"name\":\"内径\",\"value\":\"20\",\"unit\":\"mm\"}]},{\"name\":\"测量点\",\"data\":[{\"name\":\"个数\",\"value\":\"6\",\"unit\":\"个\"},{\"name\":\"分布方式\",\"value\":\"等环\",\"unit\":\"\"},{\"name\":\"安装孔直径\",\"value\":\"6\",\"unit\":\"mm\"},{\"name\":\"开孔角度\",\"value\":\"7\",\"unit\":\"度\"}]},{\"name\":\"安装座\",\"data\":[{\"name\":\"连接法兰直径\",\"value\":\"12\",\"unit\":\"mm\"},{\"name\":\"连接法兰厚度\",\"value\":\"12\",\"unit\":\"mm\"},{\"name\":\"安装螺栓数量\",\"value\":\"7\",\"unit\":\"个\"}]},{\"name\":\"焊接点\",\"data\":[{\"name\":\"A\",\"value\":\"7\",\"unit\":\"\"},{\"name\":\"B\",\"value\":\"7\",\"unit\":\"\"},{\"name\":\"C\",\"value\":\"7\",\"unit\":\"mm\"}]}]",
  //     "type": "整流罩",
  //     "name": "3335号",
  //     "standard": 0,
  //     "drawingTwo": "https://img-s.msn.cn/tenant/amp/entityid/AA1Dw8W7.img?w=768&h=522&m=6",
  //     "drawingThree": "/models/_model1.stl"
  //   },
  //   {
  //     "createBy": null,
  //     "createTime": null,
  //     "updateBy": null,
  //     "updateTime": null,
  //     "remark": null,
  //     "id": 3,
  //     "createdBy": "职工2号",
  //     "createdTime": "2017-10-15",
  //     "updatedBy": "职工34号",
  //     "updatedTime": "2007-10-04",
  //     "parameter": "[{\"name\":\"基本参数\",\"data\":[{\"name\":\"长度\",\"value\":\"12023423423343\",\"unit\":\"mm\"},{\"name\":\"形状\",\"value\":\"圆筒\",\"unit\":\"\"},{\"name\":\"外径\",\"value\":\"30\",\"unit\":\"mm\"},{\"name\":\"内径\",\"value\":\"20\",\"unit\":\"mm\"}]},{\"name\":\"测量点\",\"data\":[{\"name\":\"个数\",\"value\":\"6\",\"unit\":\"个\"},{\"name\":\"分布方式\",\"value\":\"等环\",\"unit\":\"\"},{\"name\":\"安装孔直径\",\"value\":\"6\",\"unit\":\"mm\"},{\"name\":\"开孔角度\",\"value\":\"7\",\"unit\":\"度\"}]},{\"name\":\"安装座\",\"data\":[{\"name\":\"连接法兰直径\",\"value\":\"12\",\"unit\":\"mm\"},{\"name\":\"连接法兰厚度\",\"value\":\"12\",\"unit\":\"mm\"},{\"name\":\"安装螺栓数量\",\"value\":\"7\",\"unit\":\"个\"}]},{\"name\":\"焊接点\",\"data\":[{\"name\":\"A\",\"value\":\"7\",\"unit\":\"\"},{\"name\":\"B\",\"value\":\"7\",\"unit\":\"\"},{\"name\":\"C\",\"value\":\"7\",\"unit\":\"mm\"}]}]",
  //     "type": "套管",
  //     "name": "33号",
  //     "standard": 0,
  //     "drawingTwo": "https://img-s.msn.cn/tenant/amp/entityid/AA1Dw8W7.img?w=768&h=522&m=6",
  //     "drawingThree": "/models/_model1.stl"
  //   },
  //   {
  //     "createBy": null,
  //     "createTime": null,
  //     "updateBy": null,
  //     "updateTime": null,
  //     "remark": null,
  //     "id": 4,
  //     "createdBy": "职工2号",
  //     "createdTime": "2017-03-05",
  //     "updatedBy": "职工1号",
  //     "updatedTime": "2009-12-03",
  //     "parameter": "[{\"name\":\"基本参数\",\"data\":[{\"name\":\"长度\",\"value\":\"120\",\"unit\":\"mm\"},{\"name\":\"形状\",\"value\":\"圆筒\",\"unit\":\"\"},{\"name\":\"外径\",\"value\":\"30\",\"unit\":\"mm\"},{\"name\":\"内径\",\"value\":\"20\",\"unit\":\"mm\"}]},{\"name\":\"测量点\",\"data\":[{\"name\":\"个数\",\"value\":\"6\",\"unit\":\"个\"},{\"name\":\"分布方式\",\"value\":\"等环\",\"unit\":\"\"},{\"name\":\"安装孔直径\",\"value\":\"6\",\"unit\":\"mm\"},{\"name\":\"开孔角度\",\"value\":\"7\",\"unit\":\"度\"}]},{\"name\":\"安装座\",\"data\":[{\"name\":\"连接法兰直径\",\"value\":\"12\",\"unit\":\"mm\"},{\"name\":\"连接法兰厚度\",\"value\":\"12\",\"unit\":\"mm\"},{\"name\":\"安装螺栓数量\",\"value\":\"7\",\"unit\":\"个\"}]},{\"name\":\"焊接点\",\"data\":[{\"name\":\"A\",\"value\":\"7\",\"unit\":\"\"},{\"name\":\"B\",\"value\":\"7\",\"unit\":\"\"},{\"name\":\"C\",\"value\":\"7\",\"unit\":\"mm\"}]}]",
  //     "type": "支杆/椭圆筒支杆",
  //     "name": "4号",
  //     "standard": 1,
  //     "drawingTwo": "https://img-s.msn.cn/tenant/amp/entityid/AA1Dw8W7.img?w=768&h=522&m=6",
  //     "drawingThree": "/models/_model1.stl"
  //   },
  //   {
  //     "createBy": null,
  //     "createTime": null,
  //     "updateBy": null,
  //     "updateTime": null,
  //     "remark": null,
  //     "id": 5,
  //     "createdBy": "职工1号",
  //     "createdTime": "2013-11-29",
  //     "updatedBy": "职工2号",
  //     "updatedTime": "2021-04-30",
  //     "parameter": "[{\"name\":\"基本参数\",\"data\":[{\"name\":\"长度\",\"value\":\"120\",\"unit\":\"mm\"},{\"name\":\"形状\",\"value\":\"圆筒\",\"unit\":\"\"},{\"name\":\"外径\",\"value\":\"30\",\"unit\":\"mm\"},{\"name\":\"内径\",\"value\":\"20\",\"unit\":\"mm\"}]},{\"name\":\"测量点\",\"data\":[{\"name\":\"个数\",\"value\":\"6\",\"unit\":\"个\"},{\"name\":\"分布方式\",\"value\":\"等环\",\"unit\":\"\"},{\"name\":\"安装孔直径\",\"value\":\"6\",\"unit\":\"mm\"},{\"name\":\"开孔角度\",\"value\":\"7\",\"unit\":\"度\"}]},{\"name\":\"安装座\",\"data\":[{\"name\":\"连接法兰直径\",\"value\":\"12\",\"unit\":\"mm\"},{\"name\":\"连接法兰厚度\",\"value\":\"12\",\"unit\":\"mm\"},{\"name\":\"安装螺栓数量\",\"value\":\"7\",\"unit\":\"个\"}]},{\"name\":\"焊接点\",\"data\":[{\"name\":\"A\",\"value\":\"7\",\"unit\":\"\"},{\"name\":\"B\",\"value\":\"7\",\"unit\":\"\"},{\"name\":\"C\",\"value\":\"7\",\"unit\":\"mm\"}]}]",
  //     "type": "支杆/圆形筒支杆",
  //     "name": "5号",
  //     "standard": 0,
  //     "drawingTwo": "https://img-s.msn.cn/tenant/amp/entityid/AA1Dw8W7.img?w=768&h=522&m=6",
  //     "drawingThree": "/models/_model1.stl"
  //   }
  // ]

      // 默认展开所有类型
        Object.keys(this.filteredComponentTree).forEach(level2Name => {
        this.$set(this.expandedTypes, level2Name, true);
        const level3Group = this.filteredComponentTree[level2Name];
        Object.keys(level3Group).forEach(level3Name => {
          if(level3Name !== '') {
            this.$set(this.expandedSubTypes, level2Name + '-' + level3Name, true);
          }
        });
      });

      // 默认选中第一个元件（如果有）
      if (this.components.length > 0) {
        this.selectComponent(this.components[0]);
      }
    },
    toggleSubTypeExpand(key) {
      this.$set(this.expandedSubTypes, key, !this.expandedSubTypes[key]);
    },
    // 修改loadComponents中默认展开逻辑，默认展开二级目录和三级目录
    // selectComponent(component) {
    //   console.log('选中元件，模型路径:', component.drawingThree);
    //   this.activeComponent = component;
    //   this.scale = 1;
    //   this.resetImageTransform();

    //   this.$nextTick(() => {
    //     this.initThree();
    //     if (component.drawingThree) {
    //       this.loadModel(component.drawingThree);
    //     }
    //   });
    //   if (component.drawingThree) {
    //     this.loadModel(component.drawingThree);
    //   } else {
    //     // 如果没有三维模型，清空场景中的模型
    //     if (this.threeModel) {
    //       this.threeScene.remove(this.threeModel);
    //       this.threeModel = null;
    //     }
    //   }
    // },
    selectComponent(component) {
      console.log('加载模型路径:', component.drawingThree);
      this.activeComponent = component;
      this.modelScale = 1;
      this.modelRotation = { x: 0, y: 0, z: 0 };
    },
    toggleTypeExpand(typeName) {
      this.$set(this.expandedTypes, typeName, !this.expandedTypes[typeName]);
    },
    beforeDestroy() {
      this.disposeThree();
    },
    resetImageTransform() {
      this.$nextTick(() => {
        const img = this.$refs.modelImage;
        if (img) {
          img.style.transform = "scale(1) rotate(0deg)";
        }
      });
    },
    zoom(factor) {
      this.modelScale.x *= factor;
      this.modelScale.y *= factor;
      this.modelScale.z *= factor;
    },
    toggleFullscreen() {
      const container = this.$el.querySelector(".model-container");
      if (!container) return;
      if (!document.fullscreenElement) {
        container.requestFullscreen?.();
      } else {
        document.exitFullscreen?.();
      }
    },
    rotateModel() {
      this.modelRotation.y += Math.PI / 2;
    },
    openParameterEditor() {
      // 将参数解析成编辑格式
      this.editParameters = [];
      this.parsedParameters.forEach((group) => {
        group.data.forEach((param) => {
          this.editParameters.push({
            label: param.name,
            value: param.value,
            unit: param.unit,
          });
        });
      });
      this.editDialogVisible = true;
    },
    async saveParameters() {
      try {
        // 将编辑参数重新组装成原始结构
        // 这里简单处理为只更新value，保持unit不变，按group拆分
        // 先构造一个map方便赋值
        const paramMap = {};
        this.editParameters.forEach((p) => {
          paramMap[p.label] = { value: p.value, unit: p.unit };
        });

        // 重新构造参数数组结构
        const newParams = this.parsedParameters.map((group) => {
          return {
            name: group.name,
            data: group.data.map((param) => {
              const edited = paramMap[param.name];
              return {
                name: param.name,
                value: edited ? edited.value : param.value,
                unit: edited ? edited.unit : param.unit,
              };
            }),
          };
        });

        await updateProbeComponent({
          ...this.activeComponent,
          parameter: JSON.stringify(newParams),
        });

        this.activeComponent.parameter = JSON.stringify(newParams);
        this.editDialogVisible = false;
        this.$message.success("参数更新成功");
      } catch (error) {
        this.$message.error("保存失败");
      }
    },
  },
};
</script>

<style scoped>
/* 修复核心样式 */
.probe-container {
  display: flex;
  height: calc(100vh - 84px);
  background: #f5f6fa;
  padding: 16px;
  gap: 16px;
}

.tree-node .node-header {
  font-weight: bold;
  font-size: 16px;
  padding: 8px 12px;
  user-select: none;
  display: flex;
  align-items: center;
  gap: 6px;
}

.sub-category {
  margin-left: 16px; /* 二级目录缩进 */
  /* border-left: 2px solid #409eff; */
  margin-bottom: 8px;
}

.sub-header {
  font-weight: 600;
  font-size: 14px;
  padding: 6px 12px;
  user-select: none;
  display: flex;
  align-items: center;
  gap: 6px;
  background: white;
  border-radius: 4px;
}

.component-list {
  margin-left: 32px; /* 三级目录再缩进 */
}

.component-list-panel {
  width: 280px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 12px;
}

.search-box {
  margin-bottom: 12px;
}

.component-items {
  max-height: calc(100vh - 160px);
  overflow-y: auto;
}

.component-item {
  padding: 6px 12px;
  margin: 4px 0;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.component-item:hover {
  background-color: #f0f9ff;
}

.component-item.active {
  background-color: #75797d;
  color: white;
}

.item-id {
  color: #909399;
  font-size: 12px;
  margin-right: 8px;
}

.item-name {
  flex-grow: 1;
  color: #303133;
}

.model-viewer {
  flex: 1;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 16px;
}

.model-container {
  width: 100%;
  height: 100%;
  background: #f8f9fa;
  border-radius: 4px;
  position: relative;

  /* 新增 */
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 垂直居中 */
}


.model-image {
  max-width: 100%;
  max-height: 75vh;
  object-fit: contain;
}

.model-tools {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(255,255,255,0.9);
  padding: 6px;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  color: #333; /* 设置字体和图标颜色为深色 */
}

.parameter-panel {
  width: 360px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 16px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.parameter-group {
  margin-bottom: 24px;
}

.group-title {
  color: #409eff;
  font-size: 14px;
  border-left: 3px solid #409eff;
  padding-left: 8px;
  margin: 0 0 12px 0;
}

.parameter-item {
  flex: 0 0 calc(50% - 6px); /* 两列布局，减去间距一半 */
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 8px;
  word-break: break-word;
  overflow-wrap: break-word;
}

.parameter-items-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.param-name {
  color: #606266;
  font-size: 14px;
  max-width: 40%; /* 限制名称最大宽度 */
  white-space: nowrap; /* 名称不换行 */
  overflow: hidden;
  text-overflow: ellipsis;
}
.param-value {
  color: #303133;
  font-weight: 500;
  max-width: 55%; /* 限制值最大宽度 */
  white-space: normal; /* 允许换行 */
  word-break: break-word;
}
.sub-sub-category {
  margin-left: 16px; /* 三级目录缩进 */
  margin-bottom: 8px;
}

.sub-sub-header {
  font-weight: 500;
  font-size: 13px;
  padding: 4px 12px;
  user-select: none;
  display: flex;
  align-items: center;
  gap: 6px;
  background: #f9fafb;
  border-radius: 4px;
  cursor: pointer;
}

.model-three-container {
  width: 100%;
  height: 75vh;
  background: #f0f0f0;
  border-radius: 4px;
  position: relative;
}


</style>
